<?php
namespace app\api\service\v1;
/*
 * content : 登录服务类
 * Author  : Songyicong 
 * time    : 2018-05-02 09:26:43 
 * email   : m13726262373@163.com 
 */

 use app\api\service\BaseService;
 use app\api\model\v1\User as UserModel;
 use app\api\model\v1\UserAuth as UserAuthModel;
 use app\api\extra\Utils;
 use think\Db;
 use app\api\extra\Email;
 use think\Cache;
 use sycapi\wechat\Wechat;
 use think\Env;
 use think\Response;

 class LoginService extends BaseService{

    /** 微信登录 */
    public static function setWechatLogin($params = []){
        
        // 将 access_token 存放到state
        if(empty($params['state'])){
            $params['state'] = "access_token_restapi";
        }
        Cache::set("access_token_".$params['access_token'],$params['state']);
        $oauth = Wechat::oauth();
        // url 链接 
        $url = $oauth->getOauthRedirect(Env::get('wechat_login_callback'),$params['access_token']);
        return $url;
    }
    
    /** 微信回调 */
    public static function wechatCallback($params = []){
        // 获取到code 和 access_token
        $code = $params['cpde'];
        $oauth = Wechat::oauth();
        // 获取 access_token
        $access_params = $oauth->getOauthAccessToken();
        if(!$access_params){
            return self::sendError(100209, 'wechat server is error',500); 
        }
        $access_token = $access_params['access_token'];
        $openid = $access_params['openid'];
        // 开始获取用户信息
        $wechatUser = $oauth->getOauthUserInfo($access_token,$openid);
        if(!$wechatUser){
            return self::sendError(100209, 'wechat server is error',500); 
        }
        // 开始保存操作
        if($user = UserModel::getUnionUser($wechatUser['unionid'])){
            // 表示已经注册过
            $data['user_name'] = $wechatUser['nickname'];
            $data['sex'] = $wechatUser['sex'];
            // $data[''] = $wechatUser['province'];
            // $data[''] = $wechatUser['city'];
            // $data[''] = $wechatUser['country'];
            $data['header_url'] = $wechatUser['headimgurl'];
            $data['str'] = $wechatUser['privilege'];
        }else{
            //将信息添加进去
            $data['user_name'] = $wechatUser['nickname'];
            $data['sex'] = $wechatUser['sex'];
            // $data[''] = $wechatUser['province'];
            // $data[''] = $wechatUser['city'];
            // $data[''] = $wechatUser['country'];
            $data['header_url'] = $wechatUser['headimgurl'];
            $data['str'] = $wechatUser['privilege'];
        }
    }

    /** 普通登录 */
    public function setLoginNormal($params = []){
        if(empty($params['login_name']) || empty($params['password']) || empty($params['type']))
            return self::sendError(100201, 'the default parameter cannot be empty',200);
        // 判断登录信息是否正确
        $user = UserModel::getLoginUser($params['login_name']);
        if($user&& md5($params['password']) == $user['password']){
            // 开始判断密码是否正确
            $userAuth = UserAuthModel::isAuth($user['id']);
            $data['update_time'] = time();
            $data['type'] = $params['type'];
            // 生成open_id
            $openid = Utils::getOpenId($params['access_token'],$user['id'],$user['auth_num']);
            $data['open_id'] = $openid;
            if(!$userAuth){
                $data['create_time'] = time();
                $data['user_id'] = $user['id'];
                $data['ip'] = get_client_ip();
                $data['access_token'] = $params['access_token'];
                $data['auth_num'] = $user['auth_num'];
                $data['name'] = $user['user_name'];
                $aid = Db::name('user_auth')->insertGetId($data);
            }else{
                $data['ip'] = get_client_ip();
                $data['access_token'] = $params['access_token'];
                $data['auth_num'] = $user['auth_num'];
                $data['name'] = $user['user_name'];
                $aid = Db::name('user_auth')->where('user_id',$user['id'])->update($data);
            }
            $return['openid'] = $openid;
            $return['auth_num'] = $user['auth_num'];
            return self::returnmsg(200, 'success', $return, []);
        } else{
            return self::sendError(100202, 'password is error',200);        
        }
        // 登录名错误
        return self::sendError(100202, 'login name is error',200);        
    }

    /** 邮箱登录 */
    public function setLoginEmail($params = []){
        if(empty($params['email']) || !isEmail($params['email']))
            return self::sendError(100204, 'email is error',200);
        // 用 email 是否存在
        if(!UserModel::isRegistEmail($params['email']))
            return self::sendError(100205,'email expired',200);
        // 邮箱是否验证
        if(!UserModel::isEmailState($params['email']))
            return self::sendError(100206,'email is not verified, please verify the email',200);
        if(Email::sendLogin($params['email'])){
            return self::returnmsg(200, 'code is send', [], []);
        }
        return self::sendError(100207,'unknown mistake',200);   
    }

    /** 邮箱验证 */
    public function isVerifyEmailCode($params = []){
        $emails = UserModel::isRegistEmail($params['email']);
        if(empty($params['email']) || !isEmail($params['email']) || !$emails)
            return self::sendError(100204, 'email is error',200);
        if(empty($params['code'])||empty($params['type'])){
            return self::sendError(100201,'the default parameter cannot be empty',200);
        }
        if(Email::verifyCode('login_'.$params['email'],$params['code'])){
            // 开始判断密码是否正确
            $userAuth = UserAuthModel::isAuth($emails['id']);
            
            $data['update_time'] = time();
            $data['type'] = $params['type'];
            // 生成open_id
            $openid = Utils::getOpenId($params['access_token'],$emails['id'],$emails['auth_num']);
            $data['open_id'] = $openid;
            if(!$userAuth){
                $data['create_time'] = time();
                $data['user_id'] = $emails['id'];
                $data['ip'] = get_client_ip();
                $data['access_token'] = $params['access_token'];
                $data['auth_num'] = $emails['auth_num'];
                $data['name'] = $emails['user_name'];
                $aid = Db::name('user_auth')->insertGetId($data);
            }else{
                $data['ip'] = get_client_ip();
                $data['access_token'] = $params['access_token'];
                $data['auth_num'] = $emails['auth_num'];
                $data['name'] = $emails['user_name'];
                $aid = Db::name('user_auth')->where('user_id',$emails['id'])->update($data);
            }
            $return['openid'] = $openid;
            $return['auth_num'] = $emails['auth_num'];
            return self::returnmsg(200, 'success', $return, []);
        }
        return self::sendError(100208,'code is error',200);   
    }

 }
